<?php
namespace app\controller;

use app\BaseController;
use app\services\JwtService;
use think\request;
use \think\facade\Db;
use app\model\Teacher;
use app\model\Student;
use think\captcha\facade\Captcha;

/**
 * 登陆控制器
 */
class Login extends BaseController
{
    /**
     * 登录api
     * @param string username 用户名
     * @param string password 密码
     * @param string type ['student','teacher'] 学生|教师
     */
    public function index(Request $request)
    {
        if($request->isPost()){
            $params = $request->param() ;
            $username = trim($params['username']);
            $password = trim($params['password']);
            $type = trim($params['type']);
            $captcha = trim($params['captcha']);
            $user=null;
            if( !captcha_check($captcha )){
                return resultError('验证码错误');
            }
            if($type=='student'){
                $user=Student::find($username);
            }else{
                $user=Teacher::find($username);
            }
            if ($user == null) {
                return resultError('无此用户');
            }
            if(\password_verify($password,$user['password']) == false){
                return resultError('密码错误');
            }
            $user = $this->convertUser($user,$type);
            $jwt = new JwtService();
            $token = $jwt->getToken($user);
            return resultSuccess(['token'=>$token,'desc'=>$user['desc']]);
        }else{
            return resultError('表单类型错误');
        }
    }

    /**
     * 将数据库中的用户模型转换为前端用户模型
     * @param string $user 用户名字
     * @param string $role 角色类型
     * @return mixed userInfo 转换后的用户
     */
    private function convertUser($user,$role){
        $userInfo=$user;
        $userInfo['username']=$user['name'];
        $userInfo['realname']=$user['name'];
        $userInfo['desc']=$role;
        if($role=='student'){
            $userInfo['userId'] = $user['SID'];
        }else{
            $userInfo['userId'] = $user['TID'];
            if($user['job']==0){
                $userInfo['desc'] = 'manager';
            }else{
                $userInfo['desc'] = 'teacher';
            }
        }
        return $userInfo;
    }

    /**
     * 获取验证码
     */
    public function getCaptchaCode(){
        return @Captcha::create();
    }

    /**
     * 测试验证
     */
    public function testVerify(){
        $value = $this->request->param('verifyCode');
        if( !captcha_check($value )){
            return json('Fail');
        }
        return json('Success');
    }
}
